package com.itwmk.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;
@Slf4j
@ControllerAdvice(basePackages = "com.itwmk.controller")
@ResponseBody
public class GlobalExceptionHandle {
    /**
     * 处理新增用户账号名重复抛出的 SQLIntegrityConstraintViolationException
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlExceptionHandle(SQLIntegrityConstraintViolationException e){
        log.error(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")){
            String u = e.getMessage().split(" ")[2];
            String msg=u+"已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    /**
     * 处理新增用户账号名重复抛出的 SQLIntegrityConstraintViolationException
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandle(CustomException e){
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }
}
